#include <iostream>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

void writer(int wfd)
{
    const char* c = "hello:I am father\n";
    char ch[128];
    
    int count = 0;
    pid_t pid = getpid();
    while(1)
    {
        //写到数组
        //snprintf(ch,sizeof(ch),"message:%s,pid:%d,count:%d",c,pid,count);
        //写到文件缓冲区
        //write(wfd,ch,strlen(ch));
        char c = 'l';
        write(wfd,&c,1);
        //记录打了几条信息
        count++;
        //if(count == 10) break;
    }
    close(wfd);

}

void reader(int rfd)
{
    char ch[1024];
    
    int count = 10;
    pid_t pid = getpid();
    while(1)
    {
        //sleep(100);
        size_t n = read(rfd,ch,strlen(ch)-1);
        if(n>0)
        {
            printf("father get a message:%s,n:%ld\n",ch,n);
        }
        else if(n == 0)
        {
            printf("read file done\n");
            break;
        }
        else 
            break;
        if(count == 0)
            break;
    }
    close(rfd);
}
int main()
{
    int pfd[2];
    int n = pipe(pfd);
    if(n < 0)
    {
        printf("gua");
        return -1;
    }
    printf("pfd[0]:%d,pfd[1]:%d",pfd[0]/*read*/,pfd[1]/*write*/);
    pid_t id = fork();
    if(id == 0)
    {
        //child写
        close(pfd[0]);

        writer(pfd[1]);

        exit(0);
    }

    //父读
    close(pfd[1]);

    reader(pfd[0]);

    wait(NULL);
    return 1;
}
